# coding=utf-8
from datetime import datetime

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many


def record_eip() -> bool:
    # 创建一个asapi的客户端
    asapi_data = request_asapi(1, "Vpc", "2016-04-28", "DescribeEipAddresses")
    if not asapi_data:
        return False
    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for i in asapi_data['EipAddresses']['EipAddress']:
        tmp_tuple = (
            i['AllocationId'], i['IpAddress'], i['Name'], i['Bandwidth'], i['ISP'], i['InstanceType'], i['InstanceId'],
            i['Department'], i['DepartmentName'], i['ResourceGroup'], i['ResourceGroupName'], i['Status'],
            i['AllocationTime'], datetime.now())
        values_list.append(tmp_tuple)
    table = 'c_eip_info'
    fields = "allocation_id,ip_address,name,bandwidth,isp,instance_type,instance_id,department,department_name," \
             "resource_group,resource_group_name,status,create_time,record_time"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_eip_info', methods=['POST'])
def record_eip_api():
    success = record_eip()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
